﻿using System;
using ETL.Business.Handlers.ProjectActualResourceHandler;
using ETL.Business.Models;
using ETL.Common;
using ETL.Common.Logging;
//using ETL.Business.Handlers.ProjectLogHandler;

namespace ETL.Business.Helpers
{
    public class LogOn
    {
        public virtual string Execute(decimal genProjectId, decimal genTaskId, string userName, string userId)
        {
            // Log on to project
            try
            {
                // Update last ETL Actual Resource Usages
                decimal lastGenId = 0;
                string lastTaskId = null;
                string lastProjectId = null;
                ProjectActualResourceUsageModel lastActualResourceUsages =
                    (new GetLastActualResourceUsage().Execute(userId));

                if (lastActualResourceUsages != null)
                {
                    lastGenId = lastActualResourceUsages.GenActualResourceUsageId;
                    lastTaskId = lastActualResourceUsages.ActualResourceUsage.GEN_TASK_ID.ToString();
                    lastProjectId = lastActualResourceUsages.ActualResourceUsage.TASK.GEN_PROJECT_ID.ToString();
                    if (lastActualResourceUsages.EndDate == null)
                    {
                        (new UpdateActualResourceUsage()).Execute(lastGenId, lastProjectId, lastTaskId, DateTime.Now,
                                                                  userId);
                    }

                }

                // Update start date & status of task
                (new AddNewActualResourceUsage()).Execute(genProjectId.ToString(), genTaskId.ToString(), userName,
                                                          userId);
                lastActualResourceUsages = (new GetLastActualResourceUsage().Execute(userId));
                lastGenId = lastActualResourceUsages.GenActualResourceUsageId;

                (new UpdateActualResourceUsage()).Execute(lastGenId, DateTime.Now);

                // Show task 
                // --- DONE IN CONTROLLER ----
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return "Logon to task failed!";
            }
            return "Logon to task successful!";
        }
    }
}